import React, { useState } from 'react';
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import { Form, Modal } from 'antd';
import Icon from './../icon/Icon';
import styles from './styles.module.scss';

const extensions = [javascript({ jsx: true })];

interface IProps {
  label: string;
  scriptText: string | undefined;
  change(scriptText: string): void;
}

export default ({ label, scriptText, change }: IProps) => {
  const [visible, setVisible] = useState(false);
  const [codeMirrorValue, setCodeMirrorValue] = useState('');

  function show() {
    setVisible(true);
    setCodeMirrorValue(scriptText || '');
  }

  function onOk() {
    setVisible(false);
    change(codeMirrorValue);
    setCodeMirrorValue('');
  }

  function onCancel() {
    setVisible(false);
    setCodeMirrorValue('');
  }

  return (
    <div className={styles.wrap}>
      <Form.Item label={label}>
        <CodeMirror extensions={extensions} onChange={change} value={scriptText}/>
      </Form.Item>
      <Icon className={styles.screenIcon} icon='&#xe67c;' onClick={show} />
      <Modal visible={visible} title='脚本' width={1000} onCancel={onCancel} onOk={onOk}>
        <CodeMirror extensions={extensions} onChange={setCodeMirrorValue} value={codeMirrorValue} />
      </Modal>
    </div>
  );
};